﻿
Partial Class App_conversations
    Inherits MyUI.PageBaseApp

    Public CurrAccount As mDB.Account
    Public WithEvents gg As UI.GroupButton(Of Button)
    Public WithEvents gg2 As UI.GroupButton(Of LinkButton)

    'Public FromDate As Date
    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        CurrAccount = CurrUser.CurrAccount

        gg = New UI.GroupButton(Of Button)(Me.ViewState, "GROUP_SEARCH", "active")
        gg2 = New UI.GroupButton(Of LinkButton)(Me.ViewState, "GROUP_PRIVATE", "re-tweet")

        If Not Me.IsPostBack Then
            Me.ttt.Interval = 10000
            'Me.LblUserFound.Text = "-"

            Me.gg.SelectButton = Me.RbtSearchLink
            Me.gg2.SelectButton = Me.Rbt1

            SetDataPage()
        Else

        End If


    End Sub

    Private Sub SetDataPage()

        'SetListAccount()

        If CurrAccount IsNot Nothing Then

            UI.Grid.Bind(Me.GridUsers, Nothing)
            UI.Grid.Bind(Me.GridSharePosts, Nothing)
            UI.Grid.Bind(Me.GridMessage, Nothing)
            UI.Rep.Bind(Me.RptPrivate, Nothing)

            Me.PnlPrivateOrder.Visible = False

            Select Case Me.gg.SelectValue
                Case 1
                    SetListMessage()
                Case 2
                    SetListSharePost()
                Case 3
                    SetListPost()
                Case 4
                    SetPrivate()
            End Select

        End If

        Me.UpPConversations.Update()

    End Sub

    Protected Sub gg_onselected(value As String) Handles gg.Selected
        Me.ttt.Interval = 10000
        'Me.LblUserFound.Text = "-"

        SetDataPage()
    End Sub
    Protected Sub gg2_onselected(value As String) Handles gg2.Selected
        SetDataPage()
    End Sub

    'Protected Sub AccountSelect_SelectedChanged() Handles AccountSelect.SelectedChanged
    '    SetDataPage()
    'End Sub

    Protected Sub ttt_Tick(sender As Object, e As System.EventArgs) Handles ttt.Tick

        Me.ttt.Interval = 120000

        Select Case Me.gg.SelectValue
            Case 1
                DownloadMessage(False)
            Case 3
                DownloadQueryRealTime()
        End Select


        SetDataPage()

    End Sub

#Region "MESSAGE"


    Protected Sub BtnUpdateMessage_Click(sender As Object, e As System.EventArgs) Handles BtnUpdateMessage.Click

        DownloadMessage(False)

        SetDataPage()

    End Sub

    Dim data As New List(Of mDB.Message_Post)           ' post totali
    Dim post As Dictionary(Of String, mDB.Message_Post) ' tutte le menzioni
    Private Sub DownloadMessage(Reload As Boolean)

        'If MyApp.Session.GetValueDate(MyApp.Session.key.MESSAGE_LAST_UPDATE) < Now.AddSeconds(-120) Then

        'prima scarrico

        If CurrAccount.Account_Update.Message_Post_Update < Now.AddSeconds(-120) Or Reload Then

            Dim tw = New MyApp.Network.Twitter
            tw.oauth = CurrAccount.getOauth
            tw.DownloadAccountMessagePosts(CurrAccount)

            Dim AccountIds As New List(Of Integer)
            AccountIds.Add(CurrAccount.Id)

            MyApp.Task.Update.AccountPostsUpdate(AccountIds, mDB.Account.UpdatePostMode.FOLLOWER)
            'tw.DownloadAccountPostsAsync(CurrAccount.Id)

            'MyApp.Session.SetValue(MyApp.Session.key.MESSAGE_LAST_UPDATE, Now)

        End If



    End Sub

    Private Sub SetListMessage()
        Dim g = Me.GridMessage

        post = DB.TAB.Message_Post.
            BY.Message_Post.To_Account_Id(CurrAccount.Id).
            OrderBy("pubb_date desc").
            Limit(100).
        NotifyChanged(False).ToDictionary(Of String)("post_code")


        If post.Count > 0 Then

            'postclone = (From p In post Select p.Value).ToList

            Do Until post.Count = 0

                Dim currpost = post.First.Value

                Dim ct = 0
                Do Until currpost.Reply_To_Post_Code = ""

                    If post.ContainsKey(currpost.Reply_To_Post_Code) Then
                        currpost = post(currpost.Reply_To_Post_Code)
                    Else
                        Dim temppost = DB.TAB.Message_Post.BY.Message_Post.Post_Code(currpost.Reply_To_Post_Code).NotifyChanged(False).ToObj

                        If temppost Is Nothing Then
                            currpost.Reply_To_Post_Code = ""
                        Else
                            currpost = temppost
                            post.Add(temppost.Post_Code, temppost)
                        End If
                    End If

                    ct += 1
                Loop

                addpost(currpost, 0)

            Loop

            Dim Accs = DB.TAB.Account.
                Where("id", "IN", data.Select(Function(o) o.Account_Id).Distinct.ToList).
            NotifyChanged(False).ToList

            Dim dd = (From post In data Join acc In Accs On post.Account_Id Equals acc.Id Select acc, post, post.Id).ToList

            g.PageSize = 200
            UI.Grid.Bind(g, dd, {"id"})

        Else

            UI.Grid.Bind(g, Nothing)

        End If

        Me.LblUserFound.Text = MyUI.Print.TimeLong(CurrAccount.Account_Update.Message_Post_Update) ' MyUI.Print.DateTimeLong(MyApp.Session.GetValueDate(MyApp.Session.key.MESSAGE_LAST_UPDATE))

        DB.ResetChanges()

    End Sub

    Protected Sub ppp_Send() Handles ppp.Send

        'MyApp.Session.SetValue(MyApp.Session.key.MESSAGE_LAST_UPDATE, Date.MinValue)
        'CurrAccount.Account_Update.Message_Post_Update_Date = Date.MinValue
        'DB.SubmitChanges()

        ' Me.AddJScript("ff.fadeOut();")

        Me.UpPPost.Update()
        DownloadMessage(True)
        SetDataPage()



    End Sub
    Protected Sub GridMessage_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridMessage.RowCommand
        Dim g As GridView = sender
        Dim gr = UI.GridRow.GetRow(e.CommandSource)

        If gr IsNot Nothing Then

            Dim id = UI.Grid.GetKey(g, e.CommandSource)

            Dim tc = New WebApi.Twitter.TwitterClient(CurrAccount.getOauth)

            Select Case e.CommandName
                Case "SHARE"

                    Dim butt = UI.GridRow.GetLinkButton(gr, "LBtShare")

                    Dim post As Object = Nothing
                    Try

                        post = tc.PostReTweet(butt.CommandArgument)

                    Catch ex As WebApi.Net.ExceptionAPIResponse

                    End Try

                    If post Is Nothing Then
                        butt.Text = "ERROR"
                    Else
                        butt.Text = "SHARED"
                    End If

                Case "REPLY"

                    Dim butt = UI.GridRow.GetLinkButton(gr, "LBtReply")

                    Dim user = butt.CommandArgument.Split(",")(1)
                    Dim rep = butt.CommandArgument.Split(",")(0)

                    'Dim Txt = Me.TxtPost
                    'Me.TxtPost.Text = "@" & user & " "
                    Me.ppp.PostText = SF("@{0} ", user)
                    Me.ppp.Title = SF("Reply to @{0}", user)
                    Me.ppp.ReplyPostCode = rep
                    Me.UpPPost.Update()

            End Select

        End If


    End Sub
    Private Sub addpost(currpost As mDB.Message_Post, lvl As Integer)

        currpost.PostLevel = lvl
        data.Add(currpost)

        Dim cc = currpost.Post_Code

        post.Remove(currpost.Post_Code)


        'Dim oo = (From p In postclone Where p.Reply_To_Post_Code = cc).ToList


        'If oo.Count = 0 Then
        '    oo = DB.TAB.Message_Post.
        '        BY.Message_Post.Reply_To_Post_Code(cc).
        '        Where("Reply_To_Post_Code", "=", cc).
        '    ToList()
        'End If

        Dim oo = DB.TAB.Message_Post.
            BY.Message_Post.Reply_To_Post_Code(cc).
            Where("Reply_To_Post_Code", "=", cc).
        ToList()

        For Each p In oo
            addpost(p, lvl + 1)
        Next

    End Sub

#End Region

#Region "POSTS"

    Private Sub DownloadQueryRealTime()


        If MyApp.Session.GetValueDate(MyApp.Session.key.QUERY_RT_LAST_UPDATE) < Now.AddSeconds(-120) Then
            Dim QueryIds = CurrAccount.Tab_Listen_Query.ToList(Of Integer)("query_id") '  CurrUser.Tab_Query.BY.Query.Real_Time(1).ToList(Of Integer)("id")

            If QueryIds.Count > 0 Then

                MyApp.Task.Update.QueryPostsUpdate(QueryIds, mDB.Query.UpdateModeType.REALTIME)

            End If

            MyApp.Session.SetValue(MyApp.Session.key.QUERY_RT_LAST_UPDATE, Now)

        End If


    End Sub
    Protected Sub SetListPost()
        Dim g = Me.GridUsers

        'Dim dt = CurrUser.Tab_Query.
        '    REL.Query.Query_Post.
        '    BY.Query.Real_Time(1).
        '    OrderBy("pubb_date desc").
        '    Limit(100).
        'ToList(Of mDB._Query_Post)()

        Dim dt = New mDB.Group_Query(DB.TAB.Query.REL.Query.Listen_Query.BY.Listen_Query.Account_Id(CurrAccount.Id).ToList).GetLastPostFromQueries(100)

        'Dim dt = mDB._Query_Post.GetLastPostFromQueries(
        '    DB.TAB.Query.REL.Query.Listen_Query.BY.Listen_Query.Account_Id(CurrAccount.Id).ToList, 100)

        g.PageSize = 100
        UI.Grid.Bind(g, dt, {"id"})

        Dim AccCodes As New List(Of String)
        AccCodes = dt.Select(Function(o) o.Account_Code).Distinct.ToList
        ' verifica le connessioni
        'If AccCodes.Count > 0 Then
        '    Dim Conn = CurrAccount.GetConnection(AccCodes, Nothing, {mDB.Account_Link.Type.FRIENDS, mDB.Account_Link.Type.FOLLOWER})
        '    For Each f In Conn
        '        If f.Type = mDB.Account_Link.Type.FOLLOWER Then
        '            controllatutto(f.AccountCode, "FOLLOWER")
        '        Else
        '            controllatutto(f.AccountCode, "FOLLOW")
        '        End If
        '    Next
        'End If

        Me.LblUserFound.Text = MyUI.Print.TimeLong(MyApp.Session.GetValueDate(MyApp.Session.key.QUERY_RT_LAST_UPDATE))


        ' Me.UpPElaborations.Update()
    End Sub


    Protected Sub controllatutto(UserId As String, CommandName As String)

        For Each gr In Me.GridUsers.Rows

            Dim butt = UI.GridRow.GetButton(gr, "BtnFollow")
            Dim Lbl = UI.GridRow.GetLabel(gr, "LblFollower")

            If butt.CommandArgument = UserId Then


                Select Case CommandName
                    Case "FOLLOW"

                        butt.CssClass = "button_unfollow"
                        butt.Text = "UNFOLL"
                        'butt.BackColor = Drawing.Color.Red
                        butt.CommandName = "UNFOLLOW"

                    Case "UNFOLLOW"

                        butt.CssClass = "button_follow"

                        butt.Text = "FOLLOW"
                        'butt.BackColor = Nothing
                        butt.CommandName = "FOLLOW"

                    Case "FOLLOWER"
                        Lbl.Text = "FOLL U"

                End Select

                Dim updatepan = UI.GridRow.GetControl(Of UpdatePanel)(gr, "UpPElaborations")
                updatepan.Update()

            End If


        Next


    End Sub

#End Region

#Region "SHARED POST"

    Dim dt2 As DataTable

    Public Function Getddd(id As Integer) As DataTable

        Return DB.TAB.Account.
            REL.Account.Share_Detail.REL.Share_Detail.Share_Post.
            Where("Share_Detail.pubb_date", ">", Now.AddDays(-30)).
            Where("hash_id", "=", id).
            OrderBy("Share_Detail.pubb_date desc").
        ToDataTable()

    End Function


    Private Sub SetListSharePost()
        Dim dt As DataTable

        'dt = CurrAccount.Tab_Share_Post.
        '    Where("pubb_date", ">", Now.AddDays(-30)).
        '    GroupBy("hash_id").
        '    OrderBy("share_count desc").Select("count(*) as share_count").
        '    Limit(100).
        'ToDataTable()

        dt = CurrAccount.Tab_Share_Post.
            REL.Share_Post.Share_Detail.
            Where("Share_Detail.pubb_date", ">", Now.AddDays(-30)).
            GroupBy("Share_Post.hash_id").
            OrderBy("last_share_date desc").
            Select("Max(Share_Detail.pubb_date) as last_share_date", "Max(Share_post.pubb_date) as share_date").
            Limit(100).
        ToDataTable()





        Dim a = ""
        a.GetHashCode()


        Me.GridSharePosts.PageSize = 100
        UI.Grid.Bind(Me.GridSharePosts, dt)


        'Me.UpPSharePost.Update()
    End Sub
    Protected Sub GridSharePosts_PageIndexChanging(sender As Object, e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridSharePosts.PageIndexChanging

        Me.GridSharePosts.PageIndex = e.NewPageIndex

        'Me.SetDateChar()
        Me.SetListSharePost()

    End Sub

#End Region

#Region "PRIVATE"

    Protected Sub SetPrivate()
        Dim g = Me.RptPrivate


        Me.PnlPrivateOrder.Visible = True

        Dim q = CurrAccount.Tab_Private_Post.
            REL.Private_Post.ToAccount.
            SetSelect("to_account.*", "count(*) as totmess", "max(pubb_date) as maxdata").
            OrderBy("maxdata desc").
            GroupBy("to_account.id").
            Limit(100)

        Select Case Me.gg2.SelectValue
            Case "1"
            Case "2"
                q.Where("is_sent", "=", 1)
            Case "3"
                q.Where("is_sent", "=", 0)

        End Select

        UI.Grid.Bind(Me.GridPrivate, q.ToDataTable)

        'UI.Rep.Bind(g, q.ToDataTable)

    End Sub

    Protected Sub RptPrivate_ItemCommand(source As Object, e As RepeaterCommandEventArgs) Handles RptPrivate.ItemCommand

        Dim dr = UI.RepeaterRow.GetRow(e.CommandSource)
        'Dim dr = e.CommandSource.dataitemContainer
        'dataitemContainer

        'Dim id = Utils.Conv.ToInt(UI.GridRow.GetHiddenField(dr, "idaccount").Value)
        'Dim rep = UI.GridRow.GetControl(Of Repeater)(dr, "rptmess")

        Dim id = Utils.Conv.ToInt(UI.RepeaterRow.GetControl(Of HiddenField)(dr, "idaccount").Value)
        Dim rep = UI.RepeaterRow.GetControl(Of Repeater)(dr, "rptmess")

        Dim dt = DB.TAB.Private_Post.REL.Private_Post.ToAccount.BY.Private_Post.Account_Id(CurrAccount.Id, id).ToDataTable

        UI.Rep.Bind(rep, dt)


    End Sub


#End Region

    Protected Sub GridPrivate_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles GridPrivate.PageIndexChanging
        Me.GridPrivate.PageIndex = e.NewPageIndex
        SetPrivate()
    End Sub


    Protected Sub GridPrivate_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GridPrivate.RowCommand
        Dim dr = UI.GridRow.GetRow(e.CommandSource)
        'Dim dr = e.CommandSource.dataitemContainer
        'dataitemContainer

        'Dim id = Utils.Conv.ToInt(UI.GridRow.GetHiddenField(dr, "idaccount").Value)
        'Dim rep = UI.GridRow.GetControl(Of Repeater)(dr, "rptmess")

        Dim id = Utils.Conv.ToInt(UI.GridRow.GetControl(Of HiddenField)(dr, "idaccount").Value)
        Dim rep = UI.GridRow.GetControl(Of Repeater)(dr, "rptmess")

        Dim dt = DB.TAB.Private_Post.REL.Private_Post.ToAccount.BY.Private_Post.Account_Id(CurrAccount.Id, id).ToDataTable

        UI.Rep.Bind(rep, dt)
    End Sub
End Class
'Public Class GroupButton2(Of tres As {IButtonControl, WebControl})

'    Public Property CacheState As Object
'    Public Property group As String
'    Public Property cssactive As String


'    Private Buttons As New List(Of tres)
'    Private p As Page

'    Public ReadOnly Property SelectValue() As String
'        Get
'            Return Me.SelectButton.CommandArgument
'        End Get
'    End Property

'    Public Property Visible() As Boolean
'        Get
'            Return Me.Buttons(0).Visible
'        End Get
'        Set(ByVal value As Boolean)

'            For Each b In Me.Buttons
'                b.Visible = value
'            Next

'            ' newPropertyValue = value
'        End Set
'    End Property


'    Public Property SelectButtonID() As String
'        Get
'            Return Me.CacheState("_GROUP_" & Me.group)
'        End Get
'        Set(ByVal value As String)
'            Me.CacheState("_GROUP_" & Me.group) = value
'        End Set
'    End Property

'    Public Property SelectButton() As tres
'        Get
'            Return (From b As Object In Me.Buttons Where b.ID = Me.SelectButtonID).FirstOrDefault
'        End Get
'        Set(value As tres)
'            Me.SelectButtonID = DirectCast(value, Object).ID
'            SetDataButtonList()

'        End Set
'    End Property

'    Public Event Selected(value As String)


'    Sub New(cache As Object, group As String, cssactive As String)


'        Me.p = HttpContext.Current.CurrentHandler
'        Me.CacheState = cache
'        Me.group = group
'        Me.cssactive = cssactive

'        Buttons = UI.Controls.FindCommandControls(Of tres)(Me.p.Controls, group)



'        For Each b In Buttons
'            AddHandler b.Click, AddressOf BntExport_Click
'        Next

'        SetDataButtonList()

'    End Sub

'    Private Sub SetDataButtonList()

'        For Each b As Object In Buttons
'            UI.Controls.ClassSet(b, cssactive, b.ID = Me.SelectButtonID)
'        Next

'    End Sub


'    Protected Sub BntExport_Click(sender As Object, e As EventArgs)

'        Me.SelectButton = sender
'        RaiseEvent Selected(Me.SelectValue)

'    End Sub

'End Class







